﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using SYcwpb.WinForm.JCT.Controls;
using System.Runtime.InteropServices;
using SYcwpb.Helpers;

namespace SYcwpb.WinForm.JCT
{
    public partial class JCTFrm : Form
    {
        PrintDocument printDocument;
        private System.IO.Stream streamToPrint;
        SqlDataLayer sqlHelper = new SqlDataLayer();

        EmptyTrainInputFrm etTrainFrm;
        
        public ArrayList etTrainArray = new ArrayList();
        ArrayList Suf4TrainArray = new ArrayList();
        //ArrayList petTrain = new ArrayList();
        string selectTb;

        int clientX;
        int clientY;

        int userControlWidth = 0;
        int userControlHeight = 0;

        int currentpage = 0;

        Point pa;
        Point pb;

        string HeadStr;

        //JCTFrm的单列，一次只允许打开一个锯齿图窗口
        private static JCTFrm jctFrm = null;

        string LineID = CONSTDATA.UserModel.Line;   //获取用于所属线路

        private JCTFrm()
        {
            InitializeComponent();
            Size priScreen = SystemInformation.PrimaryMonitorMaximizedWindowSize;
            this.Size = priScreen;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            printDocument = new PrintDocument();
            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
        }

        public static JCTFrm GetInstance()
        {
            if (jctFrm == null || jctFrm.IsDisposed)
            {
                jctFrm = new JCTFrm();
            }
            return jctFrm;
        }

        private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
        {
            string appstr = Application.StartupPath + "\\temp.png";
            FileStream fs = new FileStream(appstr, FileMode.Open, FileAccess.Read);
            streamToPrint = (Stream)fs;

            System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);

            
            int x = e.MarginBounds.X;
            int y = e.MarginBounds.Y;
            int width = image.Width;
            int height = image.Height;
            //MessageBox.Show(e.PageBounds.X.ToString()+","+e.PageBounds.Y.ToString()+","+e.PageBounds.Height.ToString()+","+e.PageBounds.Width.ToString());
            
            if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
            {
                width = e.MarginBounds.Width;
                height = image.Height * e.MarginBounds.Width / image.Width;
                y = (e.PageBounds.Height - height) / 2;
            }
            else
            {
                height = e.MarginBounds.Height;
                width = image.Width * e.MarginBounds.Height / image.Height;
                x = (e.PageBounds.Width - width) / 2;
            }
            
            System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
            Font headFont=new Font("Arial",24F,FontStyle.Bold,GraphicsUnit.Pixel);

            e.Graphics.DrawString(HeadStr, headFont, new SolidBrush(Color.Black), new Point( 2*userControlWidth - 320 /*width / 2 - userControlWidth + 50*/, 2));
            e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);

            fs.Close();
            //File.Delete(appstr);
        }

        private void 打印锯齿图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //#region 新的打印方法
            ////
            ////MessageBox.Show(panel1.ClientSize.Height.ToString());
            ////MessageBox.Show(panel1.ClientSize.Width.ToString());

            ////MessageBox.Show(SystemInformation.PrimaryMonitorMaximizedWindowSize.Height.ToString());
            ////MessageBox.Show(SystemInformation.PrimaryMonitorMaximizedWindowSize.Width.ToString());
            ////Graphics g = panel1.CreateGraphics();

            ////
            //#endregion


            //#region 打印预览
            //PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            //printPreviewDialog.Document = printDocument;
            //try 
            //{
            //    printPreviewDialog.ShowDialog();
            //}
            //catch (Exception excep) 
            //{
            //    MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            //}  
            //#endregion
        }

        //private void 导入数据文件ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    DataFrm dataFrm = new DataFrm();
        //    dataFrm.FormClosed += new FormClosedEventHandler(DataFormClose);
        //    dataFrm.ShowDialog();
        //}

        private void DataFormClose(object sender, FormClosedEventArgs e)
        {
            string selectTb = "select distinct tbname from TableInfo";
            DataTable dt = sqlHelper.SelectDt(selectTb);
            cb_tbselect.Items.Clear();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cb_tbselect.Items.Add(dt.Rows[i]["tbname"]);
            }
        }

        private void JCTFrm_Load(object sender, EventArgs e)
        {
            string selectTb = "select distinct TableName as tbname from TableInfo where LineID = '" + LineID + "'";
            DataTable dt = sqlHelper.SelectDt(selectTb);
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                cb_tbselect.Items.Add(dt.Rows[i]["tbname"]);
            }
            //cb_tbselect.SelectedIndex = 0;
        }

        /// <summary>
        /// 获取所有该时刻表所有出勤的车体号 101,102,103 等
        /// </summary>
        /// <param name="tbname"></param>
        /// <param name="TrainIdofTwo"></param>
        private void GetLineTwoTrain(string tbname, ref ArrayList TrainIdofTwo)
        {

            string sql = "select distinct MidID from [" + tbname + "] order by MidID ASC";
            DataTable LineTwodt = new DataTable();
            try
            {
                LineTwodt = sqlHelper.SelectDt(sql);
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
                return;
            }
            TrainIdofTwo.Clear();
            for (int i = 0; i < LineTwodt.Rows.Count; i++)
            {
                TrainIdofTwo.Add(LineTwodt.Rows[i]["MidID"].ToString());
            }
        }


        /// <summary>
        /// 根据车体号统计该车体那些车次是空跑
        /// </summary>
        /// <param name="MidID">车体号</param>
        /// <param name="emptyruns"></param>
        private void GetEmptyRuns(string tbname,string MidID,ref ArrayList emptyruns)
        {
            //string sqlstr = "select distinct runs from [" + tbname + "] where Stop=0 and MidID='" + MidID + "'";
            string sqlstr = "select distinct LastID from [" + tbname + "] where MidID='" + MidID +
                            "' and LastID not in (select distinct LastID from [" + tbname + "] where Stop=0 and MidID='" + MidID + "')";
            DataTable dt = sqlHelper.SelectDt(sqlstr);
            emptyruns.Clear();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                emptyruns.Add(dt.Rows[i][0].ToString());
            }
        }


        private void panel1_MouseClick(object sender, MouseEventArgs e)
        {
            contextMenuStrip1.Show(panel1,new Point(e.X,e.Y));
        }

        private void btn_prepage_Click(object sender, EventArgs e)
        {
            currentpage--;
            this.SuspendLayout();
            this.panel1.Location = new Point(this.panel1.Location.X, this.panel1.Location.Y +  userControlHeight);
            this.ResumeLayout(false);
            this.PerformLayout();
            this.label2.Text = currentpage.ToString();
        }

        private void btn_nextpage_Click(object sender, EventArgs e)
        {
            currentpage++;
            this.SuspendLayout();
            this.panel1.Location = new Point(this.panel1.Location.X, this.panel1.Location.Y -  userControlHeight);
            this.ResumeLayout(false);
            this.PerformLayout();
            this.label2.Text = currentpage.ToString();
        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            //打印设置 
           


            pa =this.PointToScreen(new Point(0, 24));
            pb = this.PointToScreen(new Point(clientX, clientY));
            string appstr = Application.StartupPath + "\\temp.png";
            
            if (userControlHeight==0||userControlWidth==0)
            {
                return;
            }
     
            CaptureDesktop(appstr,new Rectangle(pa,new Size(userControlWidth*5,userControlHeight)));

            System.Threading.Thread.Sleep(1000);
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.AllowMargins = true;
            pageSetupDialog.MinMargins.Bottom =10;
            pageSetupDialog.MinMargins.Top = 10;
            pageSetupDialog.MinMargins.Left = 10;
            pageSetupDialog.MinMargins.Right = 10;

            pageSetupDialog.Document = printDocument;
            if (pageSetupDialog.ShowDialog() != DialogResult.OK)
                return;


            #region 打印预览
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            
            printPreviewDialog.Document = printDocument;
            try
            {
                printPreviewDialog.ShowDialog();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            #endregion
        }

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern IntPtr CreateDC(string driver, string device, IntPtr res1, IntPtr res2);

        [DllImport("gdi32.dll")] 
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, 
            int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);

        public enum TernaryRasterOperations
         {
             SRCCOPY = 0x00CC0020, /* dest = source*/
             SRCPAINT = 0x00EE0086, /* dest = source OR dest*/
             SRCAND = 0x008800C6, /* dest = source AND dest*/
             SRCINVERT = 0x00660046, /* dest = source XOR dest*/
             SRCERASE = 0x00440328, /* dest = source AND (NOT dest )*/
             NOTSRCCOPY = 0x00330008, /* dest = (NOT source)*/
             NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */
             MERGECOPY = 0x00C000CA, /* dest = (source AND pattern)*/
             MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest*/ 
             PATCOPY = 0x00F00021, /* dest = pattern*/ 
             PATPAINT = 0x00FB0A09, /* dest = DPSnoo*/
             PATINVERT = 0x005A0049, /* dest = pattern XOR dest*/
             DSTINVERT = 0x00550009, /* dest = (NOT dest)*/
             BLACKNESS = 0x00000042, /* dest = BLACK*/ 
             WHITENESS = 0x00FF0062, /* dest = WHITE*/
         };

        public static void CaptureDesktop(string sPath,Rectangle rect)
        {
            IntPtr dcTmp = CreateDC("DISPLAY", "DISPLAY", (IntPtr)null, (IntPtr)null);
            Graphics gScreen = Graphics.FromHdc(dcTmp);
            Bitmap image = new Bitmap((int)(rect.Width), (int)(rect.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics gImage = Graphics.FromImage(image);
            IntPtr dcImage = gImage.GetHdc();
            IntPtr dcScreen = gScreen.GetHdc();
            BitBlt(dcImage, 0, 0, (int)(rect.Width), (int)(rect.Height), dcScreen, (int)(rect.Left), (int)(rect.Top), TernaryRasterOperations.SRCCOPY);
            gScreen.ReleaseHdc(dcScreen);
            gImage.ReleaseHdc(dcImage);
            image.Save(sPath);
        }

        private void JCTFrm_Paint(object sender, PaintEventArgs e)
        {
            //lastGraphics=e.Graphics;
        }

        private void cb_tbselect_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectTb = cb_tbselect.SelectedItem.ToString();
            //petTrain.Clear();
        }

        private void 出库时间偏移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TimeParaSetFrm tpsFrm = new TimeParaSetFrm();
            tpsFrm.ShowDialog();
        }

        private void 生成锯齿图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (cb_tbselect.SelectedIndex == -1)
            {
                MessageBoxHelper.ShowWarning("请选择采用哪个时刻表来画锯齿图！");
                return;
            }

            selectTb = cb_tbselect.SelectedItem.ToString();
            HeadStr = selectTb + "时刻表锯齿图";

            etTrainArray.Clear();
            etTrainFrm = new EmptyTrainInputFrm(selectTb, this);
            if (etTrainFrm.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            else //先修改车次 只是去后面四位 添加Arraylist etTrainID  并赋值画图控件
            {
                this.Cursor = Cursors.WaitCursor;

                Suf4TrainArray.Clear();

                for (int i = 0; i < etTrainArray.Count; i++)
                {
                    //petTrain.Add(etTrainArray[i].ToString());
                    Suf4TrainArray.Add(etTrainArray[i].ToString());
                }
            }

            this.panel1.SuspendLayout();
            this.panel1.Controls.Clear();
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();

            clientX = this.ClientRectangle.Right - this.ClientRectangle.Left;
            clientY = this.ClientRectangle.Bottom - this.ClientRectangle.Top - 26;

            userControlWidth = clientX / 5;
            userControlHeight = clientY;

            ArrayList LineTwoTrain = new ArrayList();
            ArrayList mqTrain = new ArrayList();
            ArrayList yfqTrain = new ArrayList();
            GetLineTwoTrain(selectTb, ref LineTwoTrain);
            JCTDrawingArea[] jct = new JCTDrawingArea[LineTwoTrain.Count];
            for (int i = 0; i < jct.Length; i++)
            {
                ArrayList emptyruns = new ArrayList();
                GetEmptyRuns(selectTb, LineTwoTrain[i].ToString(), ref emptyruns);

                this.SuspendLayout();
                panel1.Height = jct.Length / 4 == 0 ? (jct.Length / 4) * userControlHeight + 25 : ((jct.Length / 4) + 1) * userControlHeight + 25;
                panel1.Location = new Point(0, 0);
                panel1.Width = clientX;

                jct[i] = new JCTDrawingArea();
                this.panel1.SuspendLayout();
                jct[i].DrawingRect = new Rectangle(0, 0, userControlWidth - 4, userControlHeight - 4);
                jct[i].LineId = Convert.ToInt32( LineID );
                jct[i].Suojin = 50;
                jct[i].LeftStX = 40;
                jct[i].EntranceTColor = System.Drawing.Color.Black;
                jct[i].EntranceTFont = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
                jct[i].ExitTColor = System.Drawing.Color.Black;
                jct[i].ExitTFont = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
                jct[i].FirstPointY = 40;
                //jct[i].RunsColor = System.Drawing.Color.Black;  
                jct[i].RunsFont = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
                jct[i].Size = new System.Drawing.Size(userControlWidth, userControlHeight);
                jct[i].TrainIdFont = new System.Drawing.Font("Arial", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
                jct[i].TrainLineColor = System.Drawing.Color.Black;
                jct[i].TrainLineWidth = 1.2F;
                jct[i].VerticalLineColor = System.Drawing.Color.Red;
                jct[i].StationFont = new Font("Arial", 10F, FontStyle.Regular, GraphicsUnit.Pixel, (byte)(0));
                jct[i].Visible = true;
                Pen Onboradpen = new Pen(jct[i].TrainLineColor, jct[i].TrainLineWidth);
                float[] Dashvalue = { 4, 4, 4, 4 };
                Onboradpen.DashPattern = Dashvalue;
                jct[i].DashPen = Onboradpen;
                jct[i].SolidPen = new Pen(jct[i].TrainLineColor, jct[i].TrainLineWidth);

                jct[i].EmptyTrain = emptyruns;
                jct[i].StrSelectTb = selectTb;
                jct[i].EtTrainId = Suf4TrainArray;

                string tra = LineTwoTrain[i].ToString();
                string selectRows = "";
                string selectFinalRow = "";
                //不同线路选择不同的端点
                if (LineID == "2")
                {
                    //selectRows = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
                    //"] where (((Start=66 or Start=67 or Start=31) and (Station=19 or Station=1)) or (Start=30 and (Station=19 or Station=1)) or Start=Station) and Stop<>2 and MidID='" + tra + "' " +
                    //"order by runs asc ,ExitT asc";

                    //selectFinalRow = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
                    //    "] where MidID='" + tra + "' and (arc_ne='#####' or (DID=50 and Station=1 and (Start=66 or Start = 67)))";
                    selectRows = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
"] where (((Start=66 or Start=67 or Start=31) and (Station=19 or Station=1) and (Destiny<>22)) or ((Start=66 or Start=67 or Start=31) and (Station=21 or Station=1) and (Destiny=22)) or (Start=22 and (Station=21 or Station=1)) or (Start=30 and (Station=19 or Station=1)) or Start=Station) and Stop<>2 and MidID='" + tra + "' " +
"order by runs asc ,ExitT asc";

                    selectFinalRow = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
                        "] where MidID='" + tra + "' and (arc_ne='#####' or (DID=50 and Station=1 and (Start=66 or Start = 67)))";
                }else if (LineID == "1")
                {
                    selectRows = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
                    "] where (((Start=66 or Start=67 or Start=31) and (Station=22 or Station=1)) or (Start=30 and (Station=22 or Station=1)) or Start=Station) and Stop<>2 and MidID='" + tra + "' " +
                    "order by runs asc ,ExitT asc";

                    selectFinalRow = "select Station as stId,Arrive as EntranceT,Depart as ExitT,MidID as trainId,LastID as runs,Start,Destiny,DID, TrainID as arc_tr from [" + selectTb +
                        "] where MidID='" + tra + "' and (arc_ne='#####' or (DID=50 and Station=1 and (Start=66 or Start = 67)))";
                }
                if (string.IsNullOrEmpty(selectRows) || string.IsNullOrEmpty(selectFinalRow))
                {
                    MessageBoxHelper.ShowError("无法识别当前用户所属线路，请确认身份登录后再重试");
                }
                
                DataTable selectDt = new DataTable();
                DataTable selectFinalDt = new DataTable();
                DataRow[] tempSelectDTRow ;
                DataRow finalRow;
                ArrayList arr = new ArrayList();
                try
                {
                    selectDt = sqlHelper.SelectDt(selectRows);

                    //如果有车超过12点才回库的特殊处理
                    int earliest = Convert.ToInt32(selectDt.Rows[0]["ExitT"]);  //找出最早出车的时间
                    for (int index = 0; index < selectDt.Rows.Count ; index++)  //最后一行不用计算
                    {
                        if (Convert.ToInt32(selectDt.Rows[index]["ExitT"]) < earliest)
                        {
                            selectDt.Rows[index]["ExitT"] = Convert.ToInt32(selectDt.Rows[index]["ExitT"]) + 86400;   //加上一天的总秒数
                        }
                    }
                    tempSelectDTRow = selectDt.Select("", "runs asc ,ExitT asc");
                    for (int k = 0; k < tempSelectDTRow.Length; k++)
                    {
                        arr.Add(tempSelectDTRow[k]);
                    }

                    selectFinalDt = sqlHelper.SelectDt(selectFinalRow);
                    if (selectFinalDt.Rows.Count > 0)
                    {
                        finalRow = selectFinalDt.Rows[0];
                        arr.Add(finalRow);
                    }
                    
                }
                catch (System.Exception es)
                {
                    MessageBoxHelper.ShowError(es.ToString());
                    return;
                }

                DataRow[] jctRows = new DataRow[arr.Count];
                for (int kk = 0; kk < jctRows.Length; kk++)
                    jctRows[kk] = (DataRow)arr[kk];


                jct[i].LineRows = jctRows;
                jct[i].Location = new Point((i % 4) * userControlWidth + userControlWidth/2 - 10, (i / 4) * userControlHeight + 25);
                this.panel1.Controls.Add(jct[i]);

                this.panel1.ResumeLayout(false);
                this.panel1.PerformLayout();

                this.Controls.Add(panel1);
                this.ResumeLayout(false);
                this.PerformLayout();
            }
            currentpage = 1;
            this.label2.Text = currentpage.ToString();
            this.Validate();

            this.Cursor = Cursors.Default;
        }


        //private void textBox1_Click(object sender, EventArgs e)
        //{
        //    ColorDialog selectDialog = new ColorDialog();
        //    selectDialog.AllowFullOpen = false;
        //    if (selectDialog.ShowDialog() == DialogResult.OK)
        //    {
        //        if (selectDialog.Color != null)
        //        {
        //            this.panel1.SuspendLayout();
        //            //选择了颜色  所以需要重画控件
        //            foreach (System.Windows.Forms.Control control in this.panel1.Controls)
        //            {
        //                if (control is JCTDrawingArea)
        //                {
        //                    JCTDrawingArea jct = (JCTDrawingArea)control;
        //                    jct.TrainLineColor = selectDialog.Color;
        //                    jct.Invalidate();
        //                }
        //                if (control is JCTDrawingAreaLine2)
        //                {
        //                    JCTDrawingAreaLine2 jct2 = (JCTDrawingAreaLine2)control;
        //                    jct2.TrainLineColor = selectDialog.Color;
        //                }
        //            }
        //            this.panel1.ResumeLayout(false);
        //            this.panel1.PerformLayout();
        //            this.textBox1.BackColor = selectDialog.Color;
        //            //this.panel1.Invalidate();
        //        }
        //    }
        //}
    }
}
